#pragma once

#include <memory>
#include <iostream>
#include <string>
#include <sys/epoll.h>
#include "Socket.hpp"
#include "Log.hpp"

class EpollServer
{
private:
    const static int ep_size = 128;
    const static int num = 128;

public:
    EpollServer(int port) : _port(port), _listensock(std::make_unique<TcpSocket>()), _epfd(-1)
    {
        _listensock->BuildListenSocket(_port);
        _epfd = epoll_create(ep_size);
        if (_epfd < 0)
        {
            LOG(FATAL, "epoll_create error!\n");
            exit(1);
        }
        LOG(INFO, "epoll_create success!\n");
    }
    void Init()
    {
        struct epoll_event event;
        event.events = EPOLLIN;
        event.data.fd = _listensock->Sockfd();
        int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, _listensock->Sockfd(), &event);
        if (n < 0)
        {
            LOG(FATAL, "epoll_add error\n");
            exit(1);
        }
        LOG(INFO, "epoll_add success\n");
    }

    void Accepter()
    {
        InetAddr addr;
        int sockfd = _listensock->Accept(&addr);
        if (sockfd >= 0)
        {
            struct epoll_event event;
            event.data.fd = sockfd;
            event.events = EPOLLIN;
            int n = epoll_ctl(_epfd, EPOLL_CTL_ADD, sockfd, &event);
            if (n < 0)
            {
                LOG(ERROR, "epoll_add error!\n");
                return;
            }
            LOG(INFO, "fd:%d epoll_add success!\n", sockfd);
        }
        else
        {
            LOG(ERROR, "epoll_add error!\n");
            return;
        }
    }

    void HandlerIO(int fd)
    {
        char buffer[4096];
        int n = ::recv(fd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
            std::string echo_str = "<html><h1>hello bite</h1></html>";
            std::string echo("HTTP/1.0 200 OK\r\nContent-Type: text/html\r\nContent-Length: " +
                             std::to_string(echo_str.size()) + "\r\n\r\n" + echo_str);
            ::send(fd, echo.c_str(), echo.size(), 0);
        }
        else if (n == 0)
        {
            LOG(DEBUG, "sockfd:%d->quit!\n", fd);
            epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            ::close(fd);
        }
        else
        {
            LOG(ERROR, "sockfd:%d->IO error!\n", fd);
            epoll_ctl(_epfd, EPOLL_CTL_DEL, fd, nullptr);
            ::close(fd);
        }
    }

    void HandlerEvent(int n)
    {
        for (int i = 0; i < n; i++)
        {
            int fd = _revs[i].data.fd;
            uint32_t revent = _revs[i].events;

            if (fd == _listensock->Sockfd())
            {
                Accepter();
            }
            else
            {
                HandlerIO(fd);
            }
        }
    }

    void Loop()
    {
        int timeout = 1000;
        while (1)
        {
            int n = epoll_wait(_epfd, _revs, num, timeout);
            switch (n)
            {
            case 0:
                LOG(DEBUG, "epoll time out!\n");
                break;
            case -1:
                LOG(DEBUG, "epoll error!\n");
                break;
            default:
                LOG(INFO, "haved event happend!, n: %d\n", n);
                HandlerEvent(n);
                break;
            }
        }
    }
    ~EpollServer()
    {
        _listensock->Close();
        if (_epfd >= 0)
            ::close(_epfd);
    }

private:
    uint16_t _port;
    std::unique_ptr<Socket> _listensock;
    struct epoll_event _revs[num];
    int _epfd;
};